iT邦幫忙

0

解LeetCode的學習筆記Day12_Integer to Roman

LFI 2025-10-03 09:39:06144 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第十二天

第十二題題目:Given an integer, convert it to a Roman numeral.
Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:

  • If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.
  • If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).
  • Only powers of 10 (I, X, C, M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form.

給定一個整數,將其轉換為羅馬數字
羅馬數字由小數位數值的轉換結果由高到低依序相加而成,將小數位數值轉換為羅馬數字有以下規則:

  • 如果值不是以 4 或 9 開頭,則選擇可以從輸入中減去的最大值的符號,將該符號附加到結果,減去其值,然後將餘數轉換為羅馬數字。
  • 如果數值以 4 或 9 開頭,則使用減法形式 ,表示從後面的符號中減去一個符號,例如,4比5(V)小1(I):IV 9比 10(X)小 1(I):IX,僅使用以下減法形式:4(IV)、9(IX)、40(XL)、90(XC)、400(CD)和 900(CM)。
  • 只有 10 的冪次方(I、X、C、M)可以連續添加最多 3 次,以表示 10 的倍數。您不能多次新增 5 ( V)、50 ( L) 或 500 ( D),如果需要增加 4 次符號,請使用減法形式

程式碼

class Solution:
    def intToRoman(self, num: int) -> str:
        val = [1000, 900, 500, 400,
               100, 90, 50, 40,
               10, 9, 5, 4,
               1]
        syms = ["M", "CM", "D", "CD",
                "C", "XC", "L", "XL",
                "X", "IX", "V", "IV",
                "I"]

        result = []
        for i, v in enumerate(val):
            while num >= v:
                num -= v
                result.append(syms[i])
        return "".join(result)

邏輯很簡單,就是當num大於該數字,就減掉,並把對應的羅馬符號加進result裡

執行過程

初始狀態

  • num = 58

當i = 6、v = 50時,num > v

  • num = num - v = 58 - 50 = 8
  • result.append(syms[6]) → result = [" L "]

當i = 10、v = 5時,num > v

  • num = num - v = 8 - 5 = 3
  • result.append(syms[10]) → result = [" L ", " V "]

當i = 12、v = 1時,num > v

  • num = num - v = 3 - 1 = 2
  • result.append(syms[12]) → result = [" L ", " V ", " I "]
  • 以上重複三次

最後就會得到result = [" L ", " V ", " I ", " I ", " I "]在join印出就是答案了


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言